﻿using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Model;

namespace ConAppCore.Test
{
    internal class TestAssemblyEx
    {
        public static void Test()
        {

            //DBAccessManager.GetDBAccessInstance(1);
            string dllPAth = @"D:\Code\UtilZ.DotnetEx\Test\TestPluginLib\bin\Debug\net8.0\TestPluginLib.dll";

            try
            {
                //AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve1;
                //AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve2;
                //Assembly assembly = Assembly.LoadFrom(dllPAth);

                //AssemblyLoadContext.Default.Resolving += Default_Resolving1;
                //AssemblyLoadContext.Default.Resolving += Default_Resolving2;
                //Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(dllPAth);

                AssemblyEx.Enable = true;
                Assembly assembly = AssemblyEx.LoadAssemblyFromPath(dllPAth);
                Type type = assembly.GetExportedTypes().FirstOrDefault(t =>
                {
                    return t.GetInterface(typeof(ICheckItem).FullName) != null;
                });
                if (type == null)
                {
                    Console.WriteLine("type == null");
                    return;
                }
                ICheckItem item = (ICheckItem)Activator.CreateInstance(type);
                item.SetIsChecked(true, true);


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static System.Reflection.Assembly Default_Resolving2(AssemblyLoadContext arg1, System.Reflection.AssemblyName arg2)
        {
            string dllPAth = $@"D:\Code\UtilZ.DotnetEx\Test\ConAppCore\bin\Debug\net8.0\plugin\{arg2.Name}.dll";
            return arg1.LoadFromAssemblyPath(dllPAth);
        }

        private static System.Reflection.Assembly Default_Resolving1(AssemblyLoadContext arg1, System.Reflection.AssemblyName arg2)
        {
            return null;
        }

        private static System.Reflection.Assembly CurrentDomain_AssemblyResolve2(object sender, ResolveEventArgs args)
        {
            string dllPAth = $@"D:\Code\UtilZ.DotnetEx\Test\ConAppCore\bin\Debug\net8.0\plugin\{args.Name.Substring(0, args.Name.IndexOf(','))}.dll";
            return Assembly.LoadFrom(dllPAth);
        }

        private static System.Reflection.Assembly CurrentDomain_AssemblyResolve1(object sender, ResolveEventArgs args)
        {
            return null;
        }
    }
}
